import { ScrollView, StyleSheet, Text, View } from 'react-native'
import CustomButton from 'src/components/button/CustomButton'
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { IS_IPHONEX, ScaleS, ScaleT, WIDTH, ONE_PIXEL } from 'src/utils/ScreenUtil'
import CustomImage from 'src/components/image/CustomImage'
import { showUsefulExpressions } from 'src/utils/ModalUtil'
import { CommonToast, DismissLoading, ShowLoading } from 'src/utils/ToastUtil'
import { getCommonLanguageList, insertCommonLanguage, updateCommonLanguage, updateSort } from 'src/utils/RequestAPI'
import CommonWordItem from 'src/pageP/message/chat-page/commponents/CommonWordItem'
import CustomBoxShadow from 'src/components/boxshadow/CustomBoxShadow'
const usefulExpressionsIH = ScaleS(60)
const usefulExpressionsH = ScaleS(usefulExpressionsIH * 4)
const statusCommand = {
  SETTING: 0,
  EDIT: 1,
  DELETE: 2
}
const CommonWordText = {
  addCommonWordText: '新增常用语',
  completed: '完成'
}
const SaveType = {
  update: 'update',
  insert: 'insert'
}
export default class CommonWordComponent extends PureComponent {
  static propTypes = {
    addCommonWord: PropTypes.func,
    itemPress: PropTypes.func,
    onCancel: PropTypes.func,
    commonModalShow: PropTypes.func,
    userId: PropTypes.number,
    isPageB: PropTypes.bool,
    style: PropTypes.oneOfType([PropTypes.object, PropTypes.array])
  }

  static defaultProps = {
    isPageB: false
  }

  constructor (props) {
    super(props)
    this.currentStatus = statusCommand.SETTING
    this.usefulExpressionsConfig = {
      onSave: this._onSave,
      onCancel: this._onCancel,
      maskPressClose: this._maskClose
    }
    this.state = {
      showAddSymbol: true,
      showDelete: false,
      showEdit: false,
      commonWordList: []
    }
  }

  render () {
    const { itemPress, userId } = this.props
    const { showAddSymbol, showDelete, showEdit, commonWordList } = this.state
    return (
      <View style={styles.commonContainer}>
        <ScrollView style={styles.commonList}
          ref={this._scrollViewRef}>
          {commonWordList.map((item, index) => {
            return (
              <CommonWordItem
                key={item.id}
                ref={`commonWordItem${index}`}
                style={styles.commonItem}
                index={index}
                item={item}
                userId={userId}
                itemPress={itemPress}
                showDelete={showDelete}
                showEdit={showEdit}
                itemH={usefulExpressionsIH}
                onEditPress={this._onEditPress}
                onSortPress={this._onSortPress}
                deleteCompleted={this._deleteCompleted}/>
            )
          })}
        </ScrollView>
        <CustomBoxShadow style={styles.commonWordAddViewShadow}>
          <CustomButton style={styles.commonWordAddView}>
            <CustomButton style={styles.commonWordTextView} onPress={this._addCommonWord}>
              {
                showAddSymbol && <View>
                  <Text style={[styles.commonWordText, styles.commonWordTextSymbol]}>+</Text>
                </View>
              }
              <Text style={styles.commonWordText}>
                {showAddSymbol ? CommonWordText.addCommonWordText : CommonWordText.completed}
              </Text>
            </CustomButton>
            <CustomButton style={styles.commonSettingView} onPress={this._commonSetting}>
              <CustomImage
                style={styles.commonSettingImg}
                source={showAddSymbol ? require('src/imgC/message/message_setting.png') : require('src/imgC/message/message_delete.png')}/>
            </CustomButton>
          </CustomButton>
        </CustomBoxShadow>
      </View>
    )
  }

  componentDidMount () {
    this._getCommonLanguageList()
  }

  _scrollViewRef = (ref) => {
    this.scrollViewCommon = ref
  }

  /**
   * 获取常用语
   * @private
   */
  _getCommonLanguageList = (type) => {
    const { userId, isPageB } = this.props
    getCommonLanguageList({
      params: {
        type: isPageB ? 'B' : 'C',
        userId: userId
      }
    }).then((data) => {
      console.info(data)
      this.setState({ commonWordList: data.data }, () => {
        if (type === 'insert') {
          const timer = setTimeout(() => {
          // 插入后 滑动的底部
            clearTimeout(timer)
            this.scrollViewCommon.scrollToEnd({ animated: true })
          }, 100)
        }
      })
    })
  }

  /**
   * 数据改变
   * @private
   */
  _itemChanged = (data) => {
    // const { commonWordList } = this.state
    const { type, item } = data
    // let newcommonWordList
    // switch (type) {
    //   case 'insert': // 插入
    //     newcommonWordList = commonWordList.concat(item)
    //     const timer = setTimeout(() => {
    //       // 插入后 滑动的底部
    //       clearTimeout(timer)
    //       this.scrollViewCommon.scrollToEnd({ animated: true })
    //     }, 100)
    //     break
    //   case 'delete': // 删除
    //     newcommonWordList = commonWordList.filter((oldItem) => {
    //       return item.id !== oldItem.id
    //     })
    //     break
    //   case 'update': // 更新
    //     newcommonWordList = commonWordList.map((oldItem) => {
    //       if (item.id === oldItem.id) { // 修改的
    //         return item
    //       }
    //       return oldItem
    //     })
    //     break
    // }
    // this.setState({ commonWordList: newcommonWordList })
    this.setState({ commonWordList: item }, () => {
      if (type === 'insert') {
        const timer = setTimeout(() => {
        // 插入后 滑动的底部
          clearTimeout(timer)
          this.scrollViewCommon.scrollToEnd({ animated: true })
        }, 100)
      }
    })
  }

  /**
   * 删出成功
   * @private
   */
  _deleteCompleted = (item) => {
    console.info('删除成功', item)
    this._itemChanged({ type: 'delete', item })
  }

  /**
   * 常用语设置
   * @private
   */
  _commonSetting = () => {
    switch (this.currentStatus) {
      case statusCommand.SETTING:// 设置,进入编辑模式
        this.currentStatus = statusCommand.EDIT
        this._setAddSymbol(false)
        this.setState({ showEdit: true })
        break
      case statusCommand.EDIT:// 编辑，进入删除模式
        this.currentStatus = statusCommand.DELETE
        this._setAddSymbol(false)
        this.setState({ showEdit: false, showDelete: true })
        break
      case statusCommand.DELETE:// 删除，进入设置状态
        this._settingStatus()
        break
    }
  }

  /**
   * 设置常用语文字
   * @param commonWordText
   * @private
   */
  _setAddSymbol = (showAddSymbol) => {
    this.setState({ showAddSymbol })
  }

  /**
   * 编辑点击
   * @private
   */
  _onEditPress = (item) => {
    const { addCommonWord } = this.props
    addCommonWord && addCommonWord()
    this.usefulExpressionsConfig.value = item.commonLanguage
    this.usefulExpressionsConfig.title = '编辑常用语'
    showUsefulExpressions(this.usefulExpressionsConfig, { saveType: SaveType.update, item })
    this.props.commonModalShow(true)
  }

  /**
   * 添加常用语的点击
   * @private
   */
  _addCommonWord = () => {
    switch (this.currentStatus) {
      case statusCommand.SETTING: // 设置
        const { addCommonWord } = this.props
        addCommonWord && addCommonWord()
        this.usefulExpressionsConfig.value = ''
        this.usefulExpressionsConfig.title = '新增常用语'
        showUsefulExpressions(this.usefulExpressionsConfig, { saveType: SaveType.insert })
        this.props.commonModalShow(true)
        break
      case statusCommand.EDIT: // 编辑
        this._settingStatus()
        break
      case statusCommand.DELETE: // 删除
        this._settingStatus()
        break
    }
  }

  /**
   * 设置状态
   * @private
   */
  _settingStatus = () => {
    this.currentStatus = statusCommand.SETTING
    this._setAddSymbol(true)
    this.setState({ showDelete: false, showEdit: false })
  }

  /**
   * 常用语添加
   * @private
   */
  _onSave = (value, closeModal, params) => {
    if (value.length <= 0) {
      CommonToast('请输入常用语')
      return
    }
    const { saveType, item } = params
    this._onCancel(closeModal, () => {
      if (saveType === SaveType.insert) { // 插入
        this._insertCommonLanguage(value)
      } else if (saveType === SaveType.update) { // 更新
        this._updateCommonLanguage(value, item)
      }
    })
  }

  /**
   * 插入常用语
   * @param value
   * @private
   */
  _insertCommonLanguage = (value) => {
    const { userId, isPageB } = this.props
    ShowLoading()
    insertCommonLanguage({
      params: {
        commonLanguage: value,
        userId,
        type: isPageB ? 'B' : 'C'
      }
    }).then((data) => {
      DismissLoading()
      this._itemChanged({
        type: 'insert',
        item: data.data
      })
    }).catch(() => {
      DismissLoading()
    })
  }

  /**
   * 修改常用语
   * @private
   */
  _updateCommonLanguage = (value, item) => {
    const { userId, isPageB } = this.props
    ShowLoading()
    updateCommonLanguage({
      params: {
        commonLanguage: value,
        id: item.id,
        userId,
        type: isPageB ? 'B' : 'C'
      }
    }).then((data) => {
      DismissLoading()
      this._itemChanged({
        type: 'update',
        item: data.data
      })
    }).catch(() => {
      DismissLoading()
    })
  }

  _onCancel = (closeModal, callback) => {
    const { onCancel } = this.props
    onCancel && onCancel()
    closeModal(callback)
  }

  _maskClose = () => {
    const { onCancel } = this.props
    onCancel && onCancel()
  }

  /**
   * 排序点击
   * @private
   */
  _onSortPress = ({ item, index }) => {
    const { commonWordList } = this.state
    const { userId } = this.props
    if (index + 1 < commonWordList.length) {
      this.networkRequest = null
      this.animate = false
      const params = {
        preId: commonWordList[index].id,
        userId
      }
      console.info(index, 'commonWordList[index + 2].id')
      if (index + 1 >= commonWordList.length - 1) { // 倒数第二条
        params.beforeId = commonWordList[index + 1].id
      } else {
        params.beforeId = commonWordList[index + 1].id
        params.afterId = commonWordList[index + 2].id
      }
      updateSort({ params }).then((data) => {
        this.networkRequest = data.data
        if (this.animate) {
          this.setState({ commonWordList: data.data })
        }
      })
      this.refs[`commonWordItem${index}`].sortDown()
      this.refs[`commonWordItem${index + 1}`].sortUp(() => {
        this.animate = true
        this._sortCallback(index)
      })
    }
  }

  /**
   * 排序完成之后回调
   * @private
   */
  _sortCallback = (index) => {
    const { commonWordList } = this.state
    commonWordList[index + 1] = commonWordList.splice(index, 1, commonWordList[index + 1])[0]
    if (this.networkRequest) {
      this.setState({ commonWordList: this.networkRequest })
    } else {
      this.setState({
        commonWordList: [...commonWordList]
      })
    }
  }
}

const styles = StyleSheet.create({
  commonContainer: {
    backgroundColor: '#ffffff'
  },
  commonContainerX: {
    paddingBottom: ScaleS(30)
  },
  commonList: {
    height: usefulExpressionsH,
    borderTopWidth: ONE_PIXEL,
    borderTopColor: '#F3F3F3'
  },
  commonItem: {},
  deleteTextImg: {
    width: ScaleS(20),
    height: ScaleS(20),
    backgroundColor: 'red'
  },
  commonText: {
    fontSize: ScaleT(15),
    color: '#666666'
  },
  commonEditImg: {
    width: ScaleS(13),
    height: ScaleS(13),
    backgroundColor: 'yellow'
  },
  commonSortImg: {
    width: ScaleS(13),
    height: ScaleS(13),
    backgroundColor: 'blue'
  },
  commonWordAddViewShadow: {
    height: ScaleS(IS_IPHONEX ? 76 : 56),
    width: WIDTH,
    backgroundColor: 'white',
    shadowRadius: ScaleS(5),
    shadowOpacity: 0.8,
    shadowColor: '#E3E5EA',
    shadowOffset: {
      width: 0,
      height: ScaleS(2)
    }
  },
  commonWordAddView: {
    height: ScaleS(56),
    width: WIDTH,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: ScaleS(20)
  },
  commonSettingView: {
    width: ScaleS(31),
    alignItems: 'center',
    justifyContent: 'center'
  },
  commonSettingImg: {
    width: ScaleS(31),
    height: ScaleS(31)
  },
  commonWordTextView: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-start'
  },
  commonWordText: {
    color: '#3C3C3C',
    fontSize: ScaleT(13),
    fontWeight: '500'
  },
  commonWordTextSymbol: {
    marginRight: ScaleS(6)
  }
})
